use std::any::Any;
use std::fmt;
use std::time::Duration;
use async_trait::async_trait;
use tracing::{trace, debug, info, warn, error};
use tokio::time::sleep;

use protoactor_rs::actor::{Actor, ActorContext, ActorError, DefaultActorContext, PID, Props};
use protoactor_rs::system::ActorSystem;

// 定义简单的消息类型
#[derive(Debug, Clone)]
struct Greeting {
    text: String,
}

// 定义响应
#[derive(Debug, Clone)]
struct GreetingResponse {
    response: String,
}

// 简单的Actor定义
struct GreetingActor;

#[async_trait]
impl Actor for GreetingActor {
    type Context = DefaultActorContext;

    // 处理消息
    async fn receive(&self, ctx: &mut Self::Context, msg: Box<dyn Any + Send>) -> Result<(), ActorError> {
        debug!("GreetingActor: received a message");
        
        // 尝试将消息解析为Greeting类型
        if let Ok(greeting) = msg.downcast::<Greeting>() {
            info!("GreetingActor: Received greeting with text: {}", greeting.text);
            
            // 创建响应并发送
            let response = GreetingResponse {
                response: format!("Response to: {}", greeting.text),
            };
            
            ctx.respond(response);
            Ok(())
        } else {
            warn!("GreetingActor: Received unknown message type");
            Ok(())
        }
    }
    
    // Actor启动时调用
    async fn started(&self, _ctx: &mut Self::Context) -> Result<(), ActorError> {
        info!("GreetingActor: started");
        Ok(())
    }
    
    // Actor停止时调用
    async fn stopping(&self, _ctx: &mut Self::Context) -> Result<(), ActorError> {
        info!("GreetingActor: stopping");
        Ok(())
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化tracing日志
    protoactor_rs::logging::init_global_logger(None, None)?;
    
    info!("Starting minimal actor example");
    
    // 创建actor系统
    let system = ActorSystem::new()?;
    info!("Actor system created");
    
    // 创建一个GreetingActor
    let props = Props::from_producer(|| GreetingActor {});
    let greeting_pid = system.spawn::<GreetingActor>(props).await?;
    info!("GreetingActor spawned with PID: {:?}", greeting_pid);
    
    // 等待Actor启动
    sleep(Duration::from_millis(500)).await;
    
    // 发送一个简单的消息
    let greeting = Greeting { text: "Hello, world!".to_string() };
    
    // 直接发送消息，不等待响应
    info!("Sending message without waiting for response");
    system.send(&greeting_pid, greeting).await?;
    
    // 等待一段时间让消息处理
    sleep(Duration::from_secs(1)).await;
    
    // 发送一个消息并等待响应
    let greeting_with_response = Greeting { text: "Hello with response request".to_string() };
    info!("Sending message and waiting for response");
    
    let result = system.request::<GreetingResponse>(&greeting_pid, greeting_with_response, Duration::from_secs(5)).await;
    
    match result {
        Ok(response) => info!("Received response: {}", response.response),
        Err(e) => error!("Error receiving response: {:?}", e),
    }
    
    // 等待一段时间让消息处理
    sleep(Duration::from_secs(1)).await;
    
    // 停止Actor
    info!("Stopping GreetingActor");
    system.stop(&greeting_pid).await?;
    
    // 等待Actor停止
    sleep(Duration::from_secs(1)).await;
    info!("Example completed successfully");
    
    Ok(())
} 